import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      //注册路由
      routes:{
        "third_page":(context)=>const ThirdPage(),
      },
      //错误路由处理，统一返回UnknownPage
      onUnknownRoute: (RouteSettings setting) => MaterialPageRoute(builder: (context) => const UnknownPage()),
      home: Scaffold(
        appBar: AppBar(title: const Text("Flutter Demo Home Page")),
        body: const FirstScreen(),
      ),
    );
  }
}

class FirstScreen extends StatefulWidget {
  const FirstScreen({super.key});

  @override
  State<FirstScreen> createState() => FirstStage();
}

class FirstStage extends State<FirstScreen> {
  String _msg='';
  @override
  Widget build(BuildContext context) {
    return Column(children: [
      Center(child: Text('Message from Second screen: $_msg')),
      Row(children: [
        FilledButton(
          // 基本路由
          onPressed: ()=> Navigator.push(context, MaterialPageRoute(builder: (context) => const SecondPage())), child: const Text('SecondPage'),
        ),
        FilledButton(
          // 命名路由
          onPressed: ()=> Navigator.pushNamed(context, 'third_page', arguments: "Hey").then((msg)=>setState(()=>_msg=msg as String)), child: const Text('ThirdPage'),
        ),
        FilledButton(
          // 未知路由
          onPressed: ()=> Navigator.pushNamed(context, 'xxxx'), child: const Text('UnknownPage'),
        )
      ])
    ]);
  }
}

class SecondPage extends StatelessWidget {
  const SecondPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Second Page")),
      body: FilledButton(
        // 回退页面
        onPressed: ()=> Navigator.pop(context), child: const Text('Back'),
      ),
    );
  }
}

class ThirdPage extends StatelessWidget {
  const ThirdPage({super.key});

  @override
  Widget build(BuildContext context) {
    //取出路由参数
    String msg = ModalRoute.of(context)?.settings.arguments as String;
    return Scaffold(
      appBar: AppBar(title: const Text("Third Page")),
      body: Column(children: [
        Text(msg),
        FilledButton(
          onPressed: ()=> Navigator.of(context).pop('Hi'), child: const Text('Back'),
        )
      ],),
    );
  }
}

class UnknownPage extends StatelessWidget {
  const UnknownPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Unknown Page")),
      body: FilledButton(
        onPressed: ()=> Navigator.pop(context), child: const Text('Back'),
      ),
    );
  }
}